using UnityEngine;
using UnityEngine.Playables;

public class AnimMovePlayableBehaviour : PlayableBehaviour
{
    protected Transform m_player;
    protected Vector3 m_startPos;
    protected Vector3 m_endPos;
    protected Vector3 m_forward;
    protected float m_time;
    protected float m_durection;
    protected bool m_ignoreRecordStartPos;

    public Transform gardeCar { get; set; }
    public float carOffset { get; set; }
    public bool changeForward { get; internal set; }
    public Vector3 changeForwardValue { get; internal set; }

    public void Initialize(Transform transform, Transform target, bool ignoreRecordStartPos)
    {
        this.m_player = transform;
        this.m_endPos = target.transform.position;
        this.m_ignoreRecordStartPos = ignoreRecordStartPos;
    }

    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        m_time += info.deltaTime;
        m_player.transform.forward = m_forward;
        m_player.transform.position = Vector3.Lerp(m_startPos, m_endPos, m_time / (float)m_durection);

        if (gardeCar)
        {
            gardeCar.transform.position = m_player.transform.position + m_forward * carOffset;
            gardeCar.transform.forward = m_forward;
        }
    }

    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {
        base.OnBehaviourPlay(playable, info);
        this.m_startPos = m_player.position;
        if (!m_ignoreRecordStartPos)
            MoveBackPlayerPlayableBehaviour.m_endPos = m_startPos;
        m_forward = m_endPos - m_startPos;
        m_forward.y = 0;
        m_durection = (float)playable.GetDuration();
    }

    public override void OnBehaviourPause(Playable playable, FrameData info)
    {
        base.OnBehaviourPause(playable, info);
        if(changeForward && m_player)
        {
            m_player.transform.forward = changeForwardValue;
        }
    }
}
